<?php
namespace App\Modules\Withdrawal\Models;


use App\Modules\User\Models\Account;
use App\Modules\User\Models\User;
use Illuminate\Database\Eloquent\Model;

/**
 * Class Withdrawal
 * @package App\Modules\User\Models
 * @property int $user_id
 * @property int $money
 * @property string $channel
 * @property string $status
 * @property int $link_id
 * @property int $rebate_id
 * @property int $order_id
 */
class Withdrawal extends Model
{
    const CHANNEL_BANK = 'bank';
    const CHANNEL_WE_CHAT_PAY = 'we_chat_pay';

    const STATUS_INIT = 'init';
    const STATUS_PROCESSING = 'processing';
    const STATUS_SUCCESS = 'success';
    const STATUS_FAIL = 'fail';

    public static $statusShow = [
        self::STATUS_INIT => "待打款",
        self::STATUS_FAIL => "提现失败",
        self::STATUS_SUCCESS => "提现成功",
        self::STATUS_PROCESSING => "提现中",
    ];
    protected $fillable = [
        'user_id',
        'title',
        'money',
        'status',
        'channel',
        'link_id',
        'rebate_id',
        'order_id',
        'certificate',
        'shop_id'
    ];

    protected $casts = [
        'rebate_id' => 'array',
        'order_id' => 'array',
        'shop_id' => 'array',
    ];

    public function success()
    {
        $this->status = self::STATUS_SUCCESS;
        $this->save();
    }

    public function fail()
    {
        if ($this->status == self::STATUS_FAIL) {
            return null;
        }
        $this->status = self::STATUS_FAIL;
        /** @var User $user */
        $user = User::query()->find($this->user_id);
        /** @var Account $account */
        $account = $user->getAccount();
        $account->outlayFail($this->money, 'withdrawal', "提现失败");
        $this->save();
    }
}
